package com.boge.ai.utils;

import com.boge.ai.entity.rag.FaqItem;
import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.Jedis;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Redis操作的方法
 */
public class RedisOperationUtils {

    private static final String REDIS_KEY_PREFIX = "faq:";
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private  Jedis jedis;
    public RedisOperationUtils() {
        this.jedis = new Jedis("localhost", 6379);
    }

    /**
     * 加载数据到Redis服务中
     * @throws IOException
     */
    public void loadFaqDataToRedis() throws IOException {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("train_zh.json");
        if (inputStream == null) {
            throw new FileNotFoundException("File not found in resources: data.json");
        }

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {

            String line;
            int index = 0;
            while ((line = reader.readLine()) != null) {
                if (line.trim().isEmpty()) continue;
                FaqItem item = objectMapper.readValue(line, FaqItem.class);
                String key = REDIS_KEY_PREFIX + index++;
                jedis.set(key, line); // 存储原始字符串，方便后续读取
            }
        }
    }

    /**
     * 根据关键字检索匹配的信息
     * @param keyword
     * @param topNum
     * @return
     * @throws IOException
     */
    public List<FaqItem> searchInstructionByKeyword(String keyword, int topNum) throws IOException {
        Set<String> keys = jedis.keys(REDIS_KEY_PREFIX + "*");
        List<FaqItem> result = new ArrayList<>();

        for (String key : keys) {
            String json = jedis.get(key);
            FaqItem item = objectMapper.readValue(json, FaqItem.class);
            if (item.getInstruction().contains(keyword)) {
                result.add(item);
            }
            if(result.size() >= topNum) {
                break;
            }
        }

        return result;
    }

}
